/**
 * Created by Sixgod on 2016/3/13.
 */
var app = angular.module('board', []);
var x = 0;
var upImg = false;

app.controller('mainCtrl', function($scope, $rootScope){
    var main = this;

    $scope.sign = '';    // 画什么图
    $scope.mouseStyle = true;
    $scope.paint = false; // 是否处于绘制状态
    $scope.imageArray = new Array();

    // 画布分层
    $scope.levels = new Array();
    $scope.levels.push(x);
    $scope.$on('new_levels', function(event, data){
        $scope.levels = data;
    });

    // 接收buttonCtrl传来的图形信号
    $scope.$on('sign-value', function(event, data) {
        $scope.sign = data;
    });

    // 所要绘制的图形的相关数据
    // 画笔
    $scope.is_solid = true;
    $scope.line_width = 5;
    $scope.color = '#000000';
    // 实虚线
    $scope.solidEvent = function(e){
        if(e){
            $scope.is_solid = true;
        }else{
            $scope.is_solid = false;
        }
    };

    // 矩形 + 圆形
    $scope.horizontal_zoom = 1;
    $scope.vertical_zoom = 1;
    $scope.horizontal_move = 0;
    $scope.vertical_move = 0;
    $scope.rect_color = '';
    $scope.circle_zoom = 1;
    $scope.$on('firstPoint', function(event, data){
        $scope.rect_f = data;
    });
    $scope.$on('finalPoint', function(event, data){
        $scope.rect_e = data;
    });
    $scope.$on('centerPoint', function(event, data){
        $scope.circlePoint = data;
    });
    $scope.$on('radius', function(event, data){
        $scope.radius = data;
    });
    $scope.rectChange = function(e){
        if($scope.sign == 'rectangular'){
            var id = x-1;
            var cvs = document.getElementById("canvas"+id);
            $scope.imageArray[x-1] = cvs.getContext("2d");
            $scope.imageArray[x-1].clearRect(0,0,$scope.imageArray[x-1]['canvas'].width,$scope.imageArray[x-1]['canvas'].height);
            $scope.imageArray[x-1].beginPath();
            var G = {};
            G.rect = function(x1,y1,x2,y2){
                $scope.imageArray[x-1].fillStyle = $scope.rect_color;
                $scope.imageArray[x-1].fillRect(x1, y1, x2 - x1, y2 - y1);
            };
            G.data = function( a, b ){
                G.x1 = a.mouseX + Number($scope.horizontal_move);
                G.y1 = a.mouseY + Number($scope.vertical_move);
                G.x2 = b.mouseX * $scope.horizontal_zoom + Number($scope.horizontal_move);
                G.y2 = b.mouseY * $scope.vertical_zoom + Number($scope.vertical_move);
                if(G.x2 <= G.x1){
                    G.x2 = G.x1; // 缩小到没有
                }
                if(G.y2 <= G.y1){
                    G.y2 = G.y1;
                }
                $scope.imageArray[x-1].save();
            };
            G.x1 = G.y1 = G.x2 = G.y2 = 0;

            G.data($scope.rect_f, $scope.rect_e);
            G.rect(G.x1,G.y1,G.x2,G.y2);
            $scope.imageArray[x-1].restore();
            $scope.imageArray[x-1].closePath();
        }

        if($scope.sign == 'circle'){
            var id = x-1;
            var cvs = document.getElementById("canvas"+id);
            $scope.imageArray[x-1] = cvs.getContext("2d");
            $scope.imageArray[x-1].clearRect(0,0,$scope.imageArray[x-1]['canvas'].width,$scope.imageArray[x-1]['canvas'].height);

            var C = {};
            C.circle = function(x1, y1, r){
                $scope.imageArray[x-1].fillStyle = $scope.rect_color;
                $scope.imageArray[x-1].beginPath();
                $scope.imageArray[x-1].arc(x1, y1, r, 0, Math.PI*2, true);
                $scope.imageArray[x-1].closePath();
                $scope.imageArray[x-1].fill();
            };
            C.data = function(a, b){
                C.x = a.mouseX + Number($scope.horizontal_move);
                C.y = a.mouseY + Number($scope.vertical_move);
                C.r = b * $scope.circle_zoom;
                $scope.imageArray[x-1].save();
            };
            C.x = C.y = C.r = 0;

            C.data($scope.circlePoint, $scope.radius);
            C.circle(C.x, C.y, C.r);
            $scope.imageArray[x-1].restore();
        }

    };

    // 直方图的模态框数据
    $scope.xData = new Array(); // 获得X轴的元素数据
    $scope.inputX = null;
    $scope.inputY = null;
    $scope.title = null;
    $scope.desObj = null;
    $scope.curX = null;
    $scope.x_inputData = new Array(); // 输入的数据对应于X轴的数组
    $scope.inputData = null;
    $scope.error_alert = false; // 警示框
    $scope.histogram_ok = false;
    // 添加X轴
    $scope.addX = function(e){
        // 判断输入有无重复
        var q = true;

        if($scope.inputX){
            for(var p in $scope.xData){
                if($scope.inputX == $scope.xData[p]){
                    q = false;
                }else{
                    q = true;
                }
            }
            if(q){
                $scope.alertErr(null);
                $scope.xData.push($scope.inputX);
            }else{
                $scope.alertErr('X轴元素输入有重复!');
            }
            $scope.inputX = null;
        }else{
            $scope.alertErr('X轴元素未输入!');
        }
    };
    // 添加数据
    $scope.add_data = function(){
        if(!isNaN($scope.inputData)){
            $scope.alertErr(null);
            // 重难点
            if($scope.xData.indexOf($scope.curX) + 1){
                if($scope.x_inputData[$scope.curX]){
                    $scope.alertErr('XY数据对应已存在!');
                }else{
                    if($scope.inputData){
                        var a = {};
                        a.x = $scope.curX;
                        a.v = $scope.inputData;
                        $scope.x_inputData.push(a);
                        $scope.alertErr(null);
                    }else{
                        $scope.alertErr('未输入数据!');
                    }
                }
                $scope.curX = null;
                $scope.inputData = null;
            }
        }else{
            $scope.alertErr('请输入数字!');
        }

    };
    // 删除元素
    $scope.delElement = function(e, xv, v){
        if(e && xv && v){
            // 删除X轴元素
            if(e == 'x'){
                for(var a in $scope.xData){
                    if($scope.xData[a] == xv){
                        // 删除X轴与数据的对应关系
                        for(var b in $scope.x_inputData){
                            if($scope.x_inputData[b].x = xv){
                                $scope.x_inputData.splice(b, 1);
                            }
                        }
                        $scope.xData.splice(a, 1);
                    }
                }
            }else{ // 删除数据对应关系
                for(var a in $scope.x_inputData){
                    if($scope.x_inputData[a].x == xv || $scope.x_inputData[a].v){
                        $scope.x_inputData.splice(a, 1);
                    }else{
                        $scope.alertErr(xv+'上没有数据!');
                        return;
                    }
                }
            }
        }else{
            $scope.alertErr('Data Error!');
        }
    };
    $scope.sure = function(e){
        if(e == 1){
            // 判断Y轴元素是否输入完整
            if(typeof $scope.inputY === 'object'){
                var name = false, min = false, max = false, spacing = false, unit = false;
                for(var h in $scope.inputY){
                    if(h == 'name' && $scope.inputY[h]){
                        name = true;
                    }
                    if(h == 'min' && $scope.inputY[h]){
                        min = true;
                    }
                    if(h == 'max' && $scope.inputY[h]){
                        max = true;
                    }
                    if(h == 'spacing' && $scope.inputY[h]){
                        spacing = true;
                    }
                    if(h == 'unit' && $scope.inputY[h]){
                        unit = true;
                    }
                }
                if(!name){
                    $scope.alertErr('Y轴量度指标未输入!');
                }else if(!min){
                    $scope.alertErr('Y轴最小值未输入!');
                }else if(!max){
                    $scope.alertErr('Y轴最大值未输入!');
                }else if(!spacing){
                    $scope.alertErr('Y轴间距未输入!');
                }else if(!unit){
                    $scope.alertErr('Y轴单位未输入!');
                }else {
                    $scope.alertErr(null);
                    $scope.histogram_ok = true;
                    $('#myModal').modal('hide');
                }
            }
        }
        if(e == 2){
            $scope.is_word = true;
            $('#myModal').modal('hide');
        }


    };
    $scope.alertErr = function(e){
        if(e){
            $scope.error_alert = true;
            $("#error_str").text(e);
        }else{
            $scope.error_alert = false;
        }
    };

    // 图片数据
    $scope.img_width = 1;
    $scope.img_height = 1;
    $scope.vertex_center = true;
    $rootScope.img_cut = false;
    $scope.$on('img-src', function(event, data){
        $scope.imgSrc = data; // 图片uri
    });

    // 文字
    $scope.is_word = false;
    $scope.editWord = '';

    // 撤销
    $scope.undo = false;

}).
controller('buttonCtrl', function($scope, $rootScope){
    $scope.handEvent = function(e){
        $scope.sign = 'hand';
        $scope.$emit('sign-value', $scope.sign);
    };
    $scope.brushEvent = function(e){
        $scope.sign = 'brush';
        $scope.$emit('sign-value', $scope.sign);
    };
    $scope.rectangularEvent = function(e){
        $scope.sign = 'rectangular';
        $scope.$emit('sign-value', $scope.sign);
        $scope.horizontal_zoom = 1;
        $scope.vertical_zoom = 1;
        $scope.horizontal_move = 0;
        $scope.vertical_move = 0;
        $scope.rect_color = '';
        $scope.circle_zoom = 1;

    };
    $scope.circleEvent = function(e){
        $scope.sign = 'circle';
        $scope.$emit('sign-value', $scope.sign);
        $scope.horizontal_zoom = 1;
        $scope.vertical_zoom = 1;
        $scope.horizontal_move = 0;
        $scope.vertical_move = 0;
        $scope.rect_color = '';
        $scope.circle_zoom = 1;
    };
    $scope.histogramEvent = function(e){
        $scope.sign = 'histogram';
        $scope.$emit('sign-value', $scope.sign);
    };
    $scope.wordEvent = function(e){
        $scope.sign = 'word';
        $scope.$emit('sign-value', $scope.sign);
        uParse('#editor', {
            rootPath: 'src/ueditor/utf8-php/'
        });
    };
    $scope.printEvent = function(e){
        var w = window.open('about:blank','image from sixgodimiss.com');
        /*w.document.write("<canvas id='result' width='950px' height='700px'>浏览器不支持canvas</canvas>");
        w.document.write("<script src='mergeCanvas.js'></script>");*/
        for(var i in $scope.imageArray){
            var myCanvas = document.getElementById("canvas"+i);
            var image    = myCanvas.toDataURL("image/png");
            //w.onload = mergeCanvas(image);
            w.document.write("<img src='"+image+"' style='position:absolute; top: 0;left: 0' alt='from sixgodimiss.com'/>");
        }

    };
    $scope.undoEvent = function(e){
        if($scope.levels.length == 1){
            var cvs = document.getElementById('canvas0').getContext("2d");
            cvs.clearRect(0,0,cvs['canvas'].width,cvs['canvas'].height);
        }else{
            $scope.levels.pop();
            x--;
        }
        if( x < 0 ){
            x = 0;
        };

        $scope.$emit('new_levels', $scope.levels);
        //console.log($scope.levels, x);
    }

}).
controller('imgCtrl', function($scope, fileReader, $rootScope){
    $scope.vertex_center = true;
    $scope.rotateValue = 0;
    // 调角度
    $(function() {
        $(".dial").knob({
            'min' : 0,
            'max' : 360,
            'cursor' : true,
            'change' : function(){
                $scope.rotateValue = $(".dial").val();
            }
        });
    });

    // 之前一直检测区域不对
    $scope.rotateDown = function(){
        change();
        /*$scope.$watch('rotateValue',function(newValue,oldValue){
            //console.log(newValue,oldValue);

            if(newValue !== oldValue || newValue!=0){
                //change(1);
            }
        });*/
    };

    $scope.getFile = function () {
        fileReader.readAsDataUrl($scope.file, $scope)
            .then(function(result) {
                $scope.imageSrc = result;
            });
    };
    // 把图片资源传到mainCtrl
    $scope.inputFile = function(e){
        $scope.sign = 'img';
        $scope.img_height = 1;
        $scope.img_width = 1;
        $scope.$emit('sign-value', $scope.sign);
        $scope.$emit('img-src', $scope.imageSrc);
        upImg = true;
    };

    // 判断旋转事件
    $scope.rotateEvent = function(e){
        if(e){
            $scope.vertex_center = true;
        }else{
            $scope.vertex_center = false;
        }
    };

    // 上传图片
    $scope.imgChange = function(){
        change();
    };
    var change = function(){
        var cvs = document.getElementById("canvas"+$rootScope.img_level);
        $scope.imageArray[$rootScope.img_level] = cvs.getContext("2d");
        $scope.imageArray[$rootScope.img_level].clearRect(0,0,$scope.imageArray[$rootScope.img_level]['canvas'].width,$scope.imageArray[$rootScope.img_level]['canvas'].height);
        $scope.imageArray[$rootScope.img_level].save();
        var img = new Image();
        img.src = $scope.imgSrc;
        img.width *= $scope.img_width;
        img.height *= $scope.img_height;
        var angle = $scope.rotateValue * Math.PI / 180; // 旋转角度
        var cx = $scope.imageArray[$rootScope.img_level]['canvas'].width/2; // 画布中心点X
        var cy = $scope.imageArray[$rootScope.img_level]['canvas'].height/2; // 画布中心点Y
        var zx = $scope.imageArray[$rootScope.img_level]['canvas'].width/2 - img.width/2; // 图片左顶点X
        var zy = $scope.imageArray[$rootScope.img_level]['canvas'].height/2 -img.height/2; // 图片左顶点Y

        // 判断是左顶点旋转还是中心点旋转
        if($scope.vertex_center){
            $scope.imageArray[$rootScope.img_level].translate(zx, zy);
            $scope.imageArray[$rootScope.img_level].rotate(angle);
            $scope.imageArray[$rootScope.img_level].translate(-zx, -zy);
        }else{
            $scope.imageArray[$rootScope.img_level].translate(cx, cy);
            $scope.imageArray[$rootScope.img_level].rotate(angle);
            $scope.imageArray[$rootScope.img_level].translate(-cx, -cy);
        }

        $scope.imageArray[$rootScope.img_level].drawImage(img, zx, zy, img.width, img.height);
        $scope.imageArray[$rootScope.img_level].restore();

        //$scope.imageArray[x].drawImage( img, 0, 0, img.width, img.height); 出现在画布左顶点
        //$scope.imageArray[x].save();
    };

    //裁剪事件
    $scope.cutEvent = function(e){
        if($scope.sign == 'img'){
            $rootScope.img_cut = true;
        }
    }
}).
controller('canvasCtrl', function($scope, $rootScope){
    var div = document.getElementsByClassName("div_canvas");
    /*
        cvs.offsetLeft = 19;
        cvs.offsetTop = 19;
    */
    // 画布相对页面边距
    var canvasMargin = {
        mouseX : div[0].offsetLeft + 19,
        mouseY : div[0].offsetTop + 19 + 10  // why+10,可能有padding或margin空隙
    };
    // 画布右下顶点
    var rightBottomCorner = {
        mouseX : canvasMargin.mouseX + 950,
        mouseY : canvasMargin.mouseY + 700
    };
    // 在画布上点下的第一个点,最后一个点
    var firstPoint = {};
    var finalPoint = {};

    // 矩形
    var G = {};
    G.rect = function(x1,y1,x2,y2){
        $scope.imageArray[x].fillStyle = $scope.rect_color;
        $scope.imageArray[x].fillRect(x1, y1, x2 - x1, y2 - y1);
    };
    G.x1 = G.y1 = G.x2 = G.y2=0;

    // 圆形
    var C = {};
    C.circle = function(x1, y1, r){
        $scope.imageArray[x].fillStyle = $scope.rect_color;
        $scope.imageArray[x].beginPath();
        $scope.imageArray[x].arc(x1, y1, r, 0, Math.PI*2, true);
        $scope.imageArray[x].closePath();
        $scope.imageArray[x].fill();
    };
    C.x1 = C.y1 = C.x2 = C.y2 = C.r = 0;

    // 鼠标移动到画布上
    $scope.over = function(e){};

    // 鼠标按下
    $scope.down = function(e){
        $scope.paint = true;
        $scope.imageArray[x] = document.getElementById('canvas'+x).getContext("2d");

        // 起始点
        var startPoint = firstPoint = curPoint(canvasMargin);

        if($scope.sign == 'brush'){
            $scope.imageArray[x].beginPath();
            // 判断实虚线
            if($scope.is_solid){
                $scope.imageArray[x].setLineDash([0,0]);
            }else {
                $scope.imageArray[x].setLineDash([30,10]);
            }
            // 移动到起始点
            $scope.imageArray[x].moveTo(startPoint.mouseX, startPoint.mouseY);
        }

        if($scope.sign == 'rectangular'){
            $scope.imageArray[x].beginPath();
            G.x1 = startPoint.mouseX;
            G.y1 = startPoint.mouseY;
        }

        if($scope.sign == 'circle'){
            C.x1 = startPoint.mouseX;
            C.y1 = startPoint.mouseY;
        }

        if($scope.sign == 'img'){
            if(upImg){
                $scope.imageArray[x].clearRect(0,0,$scope.imageArray[x]['canvas'].width,$scope.imageArray[x]['canvas'].height);
                $scope.imageArray[x].save();
                var img = new Image();
                img.src = $scope.imgSrc;
                img.width *= $scope.img_width;
                img.height *= $scope.img_height;
                $scope.imageArray[x].drawImage(
                    img,
                    $scope.imageArray[x]['canvas'].width/2 - img.width/2,
                    $scope.imageArray[x]['canvas'].height/2 -img.height/2,
                    img.width,
                    img.height
                );
                $scope.imageArray[x].restore();
            }
            upImg = false;

            if($rootScope.img_cut){
                $scope.imageArray[$rootScope.img_level] = document.getElementById('canvas'+$rootScope.img_level).getContext("2d");
            }
        }

        if($scope.sign == 'histogram'){

            var c = new Array();
            for(var a in $scope.xData){
                for(var b in $scope.x_inputData){
                    if($scope.xData[a] == $scope.x_inputData[b].x){
                        c.push($scope.x_inputData[b].v);
                    }
                }
            }

            // 基于准备好的dom，初始化echarts实例
            var myChart = echarts.init(document.getElementById('canvas'+x));

            // 指定图表的配置项和数据
            var option = {
                title : {
                    text: $scope.title,
                    x:'left'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                        type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                toolbox: {
                    /*feature: {
                        dataView: {show: true, readOnly: false},
                        magicType: {show: true, type: ['line', 'bar']},
                        restore: {show: true}
                        //saveAsImage: {show: true}
                    }*/
                },
                legend: {
                    show: true,
                    data: [$scope.desObj]
                },
                xAxis: [
                    {
                        type: 'category',
                        axisTick : {show: false},
                        data: $scope.xData
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: $scope.inputY.name,
                        min: $scope.inputY.min,
                        max: $scope.inputY.max,
                        interval: Number($scope.inputY.spacing),
                        axisLabel: {
                            formatter: '{value} '+ $scope.inputY.unit
                        }
                    }
                ],
                series: [
                    {
                        name: $scope.desObj,
                        type:'bar',
                        label: {
                            normal: {
                                show: true,
                                position: 'top'
                            }
                        },
                        data: c
                    }
                ]
            };

            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);
        }

        if($scope.sign == 'word'){
            $scope.wordStyle = {};
            $scope.wordFormat = {};
            $scope.jsonWord = xmlToJson(createXml($scope.editWord));
            $scope.wordStyle.text = '';
            $scope.wordStyle.style = '';

            // 获取JSON数据的样式
            for(var a in $scope.jsonWord['p']){
                    switch (a){
                        case '#text':
                            $scope.wordStyle.text = $scope.jsonWord['p'][a];
                            break;
                        case 'strong':
                            if($scope.jsonWord['p'][a]['span']){
                                $scope.wordStyle.text = $scope.jsonWord['p'][a]['span']['#text'];
                                $scope.wordStyle.style += $scope.jsonWord['p'][a]['span']['@attributes'].style;
                            }else{
                                $scope.wordStyle.text = $scope.jsonWord['p'][a]['#text'];
                            }
                            $scope.wordStyle.style += (a + ': true; ');
                            break;
                        case 'em':
                            if($scope.jsonWord['p'][a]['strong']){
                                $scope.wordStyle.text = $scope.jsonWord['p'][a]['strong']['#text'];
                                $scope.wordStyle.style += 'strong: true; ';
                            }
                            if($scope.jsonWord['p'][a]['span']){
                                if($scope.jsonWord['p'][a]['span']['strong']){
                                    $scope.wordStyle.text = $scope.jsonWord['p'][a]['span']['strong']['#text'];
                                    $scope.wordStyle.style += 'strong: true; ';
                                }else{
                                    $scope.wordStyle.text = $scope.jsonWord['p'][a]['span']['#text'];
                                }
                                $scope.wordStyle.style += $scope.jsonWord['p'][a]['span']['@attributes'].style;
                            }else{
                                $scope.wordStyle.text = $scope.jsonWord['p'][a]['#text'];
                            }
                            $scope.wordStyle.style += (a + ': true; ');
                            break;
                        case 'span':
                            for(var b in $scope.jsonWord['p']['span']){
                                switch (b){
                                    case '#text':
                                        $scope.wordStyle.text = $scope.jsonWord['p']['span'][b];
                                        break;
                                    case '@attributes':
                                        $scope.wordStyle.style += $scope.jsonWord['p']['span'][b].style;
                                        break;
                                    case 'em':
                                        if($scope.jsonWord['p']['span'][b]['strong']){
                                            if($scope.jsonWord['p']['span'][b]['strong']['span']){
                                                $scope.wordStyle.text = $scope.jsonWord['p']['span'][b]['strong']['span']['#text'];
                                                $scope.wordStyle.style += $scope.jsonWord['p']['span'][b]['strong']['span']['@attributes'].style;
                                            }else{
                                                $scope.wordStyle.text = $scope.jsonWord['p']['span'][b]['strong']['#text'];
                                            }
                                            $scope.wordStyle.style += 'strong: true; ';
                                        }else{
                                            $scope.wordStyle.text = $scope.jsonWord['p']['span'][b]['#text'];
                                        }
                                        $scope.wordStyle.style += (b + ': true; ');
                                        break;
                                    case 'strong':
                                        if($scope.jsonWord['p']['span'][b]['span']){
                                            $scope.wordStyle.text = $scope.jsonWord['p']['span'][b]['span']['#text'];
                                            $scope.wordStyle.style += $scope.jsonWord['p']['span'][b]['span']['@attributes'].style;
                                        }else{
                                            $scope.wordStyle.text = $scope.jsonWord['p']['span'][b]['#text'];
                                        }
                                        $scope.wordStyle.style += (b + ': true; ');
                                        break;
                                }
                            }
                            break;
                    }
                }


            if($scope.wordStyle.style && $scope.wordStyle.style!=''){
                $scope.finalStyle = finalFormat($scope.wordStyle);
            }else{
                $scope.finalStyle = {
                    'style': '',
                    'text' : $scope.wordStyle.text
                }
            }
            //console.log($scope.finalStyle);return;

            if($scope.is_word){

                // 文字颜色
                $scope.imageArray[x].fillStyle = '#000000';
                if($scope.finalStyle['color']){
                    if(art){
                        $scope.imageArray[x].strokeStyle = $scope.finalStyle['color'];
                    }else{
                        $scope.imageArray[x].fillStyle = $scope.finalStyle['color'];
                    }
                }

                // 字体
                function styleStr(){
                    var s = '';
                    s += $scope.finalStyle['em']? 'italic ':'';
                    s += $scope.finalStyle['strong']? 'bold ':'';
                    s += $scope.finalStyle['font-size']? $scope.finalStyle['font-size']+' ': '16px ';
                    s += $scope.finalStyle['font-family']? $scope.finalStyle['font-family'] : 'Arial';
                    return s;
                }
                $scope.imageArray[x].font = styleStr();
                //console.log($scope.finalStyle.text);

                // 下划线
                $scope.imageArray[x].textBaseline = $scope.finalStyle['text-decoration']?"bottom":'';

                // 内容
                var txt = '';
                if($scope.finalStyle.text && $scope.finalStyle.text!=''){
                    txt = $scope.finalStyle.text;

                    if(art){
                        $scope.imageArray[x].strokeText(txt, startPoint.mouseX, startPoint.mouseY+12);
                    }else{
                        $scope.imageArray[x].fillText(txt, startPoint.mouseX, startPoint.mouseY+12);
                    }
                }

                // 背景色
                /*$scope.imageArray[x].fillStyle = '#ffffff';
                if($scope.finalStyle['background-color']){
                    $scope.imageArray[x].fillStyle = $scope.finalStyle['background-color'];
                    $scope.imageArray[x].fillRect(startPoint.mouseX, startPoint.mouseY, $scope.imageArray[x].measureText(txt).width, 50);
                }*/
            }

            // 调整格式
            function finalFormat(a){
                var finalStyle = new Array();
                var str = a.style;
                var arr = str.split(";");
                arr.pop();
                // 去首尾括号
                for(var i in arr){
                    arr[i] = arr[i].replace(/^\s+|\s+$/g, "");
                };

                function unique(arr)
                {
                    arr.sort();
                    var re=[arr[0]];
                    for(var i = 1; i < arr.length; i++)
                    {
                        if( arr[i] != re[re.length-1])
                        {
                            re.push(arr[i]);
                        }
                    }
                    return re;
                };
                var sortArr = unique(arr);
                for(var j in sortArr){
                    var subArr = sortArr[j].split(":");
                    finalStyle[subArr[0]] = subArr[1].replace(/^\s+|\s+$/g, "");
                    /*switch (subArr[0]){
                        case 'background-color':
                            finalStyle['fillStyle1'] = subArr[1];
                            break;
                        case  'color':
                            finalStyle['fillStyle2'] = subArr[1];
                            break;
                        case 'em':
                            finalStyle['']
                    }*/
                }
                finalStyle['text'] = $scope.wordStyle.text;
                return finalStyle;
            }

            // Changes str to XML
            function createXml(str){
                if(document.all){
                    var xmlDom=new ActiveXObject("Microsoft.XMLDOM");
                    xmlDom.loadXML(str);
                    return xmlDom;
                }
                else
                    return new DOMParser().parseFromString(str, "text/xml");
            };

            // Changes XML to JSON
            function xmlToJson(xml) {
                // Create the return object
                var obj = {};
                if (xml.nodeType == 1) { // element
                    // do attributes
                    if (xml.attributes.length > 0) {
                        obj["@attributes"] = {};
                        for (var j = 0; j < xml.attributes.length; j++) {
                            var attribute = xml.attributes.item(j);
                            obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
                        }
                    }
                } else if (xml.nodeType == 3) { // text
                    obj = xml.nodeValue;
                }
                // do children
                if (xml.hasChildNodes()) {
                    for(var i = 0; i < xml.childNodes.length; i++) {
                        var item = xml.childNodes.item(i);
                        var nodeName = item.nodeName;
                        if (typeof(obj[nodeName]) == "undefined") {
                            obj[nodeName] = xmlToJson(item);
                        } else {
                            if (typeof(obj[nodeName].length) == "undefined") {
                                var old = obj[nodeName];
                                obj[nodeName] = [];
                                obj[nodeName].push(old);
                            }
                            obj[nodeName].push(xmlToJson(item));
                        }
                    }
                }
                return obj;
            };

        }

        $scope.paint = true;
    };
    $scope.mouseDrag = function(e){
        if($scope.paint){
            var endPoint = curPoint(canvasMargin);
            // 绘制溢出
            if(endPoint.mouseX >= rightBottomCorner.mouseX){
                endPoint.mouseX = rightBottomCorner.mouseX;
            }
            if(endPoint.mouseY >= rightBottomCorner.mouseY){
                endPoint.mouseY = rightBottomCorner.mouseY;
            }

            // 画笔操作
            if( $scope.sign == 'brush'){
                $scope.imageArray[x].lineTo(endPoint.mouseX, endPoint.mouseY);
                $scope.imageArray[x].lineWidth = $scope.line_width;
                $scope.imageArray[x].strokeStyle = $scope.color;
                $scope.imageArray[x].stroke();
            }

            if( $scope.sign == 'rectangular'){
                $scope.imageArray[x].clearRect(0,0,$scope.imageArray[x]['canvas'].width,$scope.imageArray[x]['canvas'].height);

                G.x2 = endPoint.mouseX;
                G.y2 = endPoint.mouseY;
                $scope.imageArray[x].save();
                G.rect(G.x1,G.y1,G.x2,G.y2);
                $scope.imageArray[x].restore();
            }

            if( $scope.sign == 'circle'){
                $scope.imageArray[x].clearRect(0,0,$scope.imageArray[x]['canvas'].width,$scope.imageArray[x]['canvas'].height);

                $scope.imageArray[x].save();
                C.x2 = endPoint.mouseX;
                C.y2 = endPoint.mouseY;
                C.r = Math.sqrt(Math.pow(C.x2 - C.x1, 2) + Math.pow(C.y2 - C.y1, 2));
                C.circle(C.x2, C.y2, C.r);
            }

            if( $scope.sign == 'img' && $rootScope.img_cut){
                //$scope.imageArray[$rootScope.img_level].clearRect(0,0,$scope.imageArray[$rootScope.img_level]['canvas'].width,$scope.imageArray[$rootScope.img_level]['canvas'].height);
                $scope.imageArray[$rootScope.img_level].save();
                $scope.imageArray[$rootScope.img_level].rect(firstPoint.mouseX, firstPoint.mouseY, endPoint.mouseX-firstPoint.mouseX, endPoint.mouseY-firstPoint.mouseY);
                $scope.imageArray[$rootScope.img_level].strokeStyle = "green";
                $scope.imageArray[$rootScope.img_level].stroke();
            }
        }
    };
    $scope.up = function(e){
        if($scope.paint){
            $scope.paint = false;

            finalPoint = curPoint(canvasMargin); // 绘制最终点

            if($scope.sign == 'brush'){
                $scope.imageArray[x].closePath();
            }
            if($scope.sign == 'rectangular'){
                $scope.$emit('firstPoint', firstPoint);
                $scope.$emit('finalPoint', finalPoint);
                $scope.imageArray[x].closePath();
            };
            if($scope.sign == 'circle'){
                $scope.$emit('centerPoint', finalPoint);
                $scope.$emit('radius', C.r);
            };
            if($scope.sign == 'img'){
                $rootScope.img_level = x;
                if($rootScope.img_cut){
                    $scope.imageArray[$rootScope.img_level].clipRect();
                }
            }

            // 画好一次直方图后,须点击确认后再行绘制
            if($scope.sign == 'histogram' && $scope.histogram_ok){
                $scope.histogram_ok = false;
            };

            // 图层叠加
            /*var next = function(){
                return '<canvas id="canvas'+ x +'" width="950px" height="700px"' +
                    'ng-mouseover="over($event)"' +
                    'ng-mousedown="down($event)"' +
                    'ng-mousemove="mouseDrag($event)"' +
                    'ng-mouseup="up($event)"' +
                    'ng-mouseleave="mouseLeave($event)"' +
                    'class="canvas">你的浏览器不支持canvas</canvas>';
            };*/
            x++;
            $scope.levels.push(x);
            $scope.$emit('new_levels', $scope.levels);
        }
    };

    $scope.mouseClick = function(e){

    };
    $scope.mouseLeave = function(){
        if($scope.sign == 'rectangular'){

        }
    };

    // 获得鼠标当前所对应的点相对于画布的位置
    var curPoint = function(x){
        var e = event || window.event;
        var endPoint = {
            mouseX : e.clientX - x.mouseX,
            mouseY : e.clientY - x.mouseY
        };
        if($scope.sign == 'rectangular' || $scope.sign == 'circle'){
            endPoint.mouseY -= 19;
        }
        return endPoint;
    }
});
